<?php

//------------------------
// 用户模型
//-------------------------
namespace app\common\model;

use com\gdl\agk\dataobject\user\UserDTO;
use com\gdl\agk\interfaces\UserServiceClient;
use think\Db;
use think\Model;
use think\Config;

class User extends Model 
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    //自动完成
    protected $auto = ['password'];

    protected function setPasswordAttr($value)
    {
        return password_hash_tp($value);
    }

    /**
     * 修改密码
     */
    public function updatePassword($uid, $password)
    {
        return $this->where("userid", $uid)->update(['password' => password_hash_tp($password)]);
    }


    public function getVerifyPhoto($id){
        $arr = Db::name('user_verify_photo')->alias('a')->where('b.id=' . $id )->field('a.id,a.identity_id,a.photo,a.status')->join('ex_user_company b','b.id=a.identity_id','left')->find();
        return $arr;
    }
    public function insertVerifyPhoto($data,$identity_id){
        $arr = $this->alias('a')->where("b.id", $identity_id)->join('ex_user_company b','b.userid=a.userid','left')->update(['a.photo_collect'=>$data['photo']]);
        if ($arr){
            $arr = Db::name('user_verify_photo')->where("identity_id", $identity_id)->delete();
        }
        return $arr;
    }
    public function updateVerifyPhotoByIdentity_id($data,$identity_id){
        $arr = Db::name('user_verify_photo')->where("identity_id", $identity_id)->update($data);
        return $arr;
    }
    /**
     * 获取用户留底照片
     */
    public function getUserPhotoCollect($identity_id){
        $result = $this->alias('a')->field('a.photo_collect')->where("b.id", $identity_id)->join('ex_user_company b','b.userid=a.userid','left')->find();
        if ($result){
            return $result['photo_collect'];
        }
        return false;
    }
    /**
     * 根据条件 查询
     * @param array $arg ['id'=>1,'name'=>'张三']
     * @param null $field
     * @return array
     */
    public function getListByArg($arg, $field = '*')
    {
        return $this->where($arg)->field($field)->select();
    }

    public function getListByArgOne($arg, $field = '*',$left_join = null)
    {
        if (!empty($left_join)){
            $table = $left_join[0];
            $conditoon = $left_join[1];
            return $this->where($arg)->field($field)->join($table,$conditoon,'left')->find();
        }else{
            return $this->where($arg)->field($field)->find();
        }
    }

    /**
     * 根据级别id和标识获取下属信息
     */
    public function getSubordinateInfoById($id, $sign) 
    {
        \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk'));
        $testDo = new UserDTO();
        $userIds = null; //下属用户id集合
        switch ($sign) {
            // 属于项目级别
            case 0 :
                //获取当前级别下的公司
                $company = Db::name('company')->where('status = 1 AND isdelete = 0 AND project_id = ' . $id)->field('id,name')->select();
                if (isset($company)) {
                    $companyIds = null; //公司id集合
                    foreach ($company as $key => $value) {
                        $companyIds .= $value['id'] . ',';
                    }
                    if (!empty($companyIds))
                        $companyIds = rtrim($companyIds, ','); //剔除最后一个，逗号

                    //获取下属公司 人员信息
                    $testDo->where = "companyid in($companyIds)";
                    $api = new UserServiceClient(null);
                    \ApiClient::build($api);
                    $rs = $api->userList($testDo);
                    $UserList = $rs->data;
                    if (isset($UserList)) {
                        foreach ($UserList as $uVal) {
                            $userIds .= $uVal['userid'] . ',';
                        }
                        if (!empty($userIds))
                            $userIds = rtrim($userIds, ','); //剔除最后一个，逗号
                    }else {
                        $userIds = null;
                    }

                    //**根据公司id查询 部门级别
                    $department = Db::name('department')->where('status = 1 AND isdelete = 0 AND company_id in (' . $companyIds . ')')->field('id,name')->select();
                    if (isset($department)) {
                        $departmentIds = null; //公司id集合
                        foreach ($department as $key => $value) {
                            $departmentIds .= $value['id'] . ',';
                        }
                        if (!empty($departmentIds))
                            $departmentIds = rtrim($departmentIds, ','); //剔除最后一个，逗号

                        //获取下属部门 人员信息
                        $testDo->where = "department in($departmentIds)";
                        $api = new UserServiceClient(null);
                        \ApiClient::build($api);
                        $rs = $api->userList($testDo);
                        $UserList = $rs->data;
                        if (isset($UserList)) {

                            foreach ($UserList as $kk => $uVal) {
                                $userIds .= ($kk == 0 ? ',' : '') . $uVal['userid'] . ',';
                            }
                            if (!empty($userIds))
                                $userIds = rtrim($userIds, ','); //剔除最后一个，逗号
                        } else {
                            $userIds = null;
                        }
                    }

                    //**根据部门id查询 职务级别
                    $position = Db::name('admin_position')->where('p_status = 1 AND isdelete = 0 AND department_id in (' . $departmentIds . ')')->field('id,name')->select();
                    if (isset($position)) {
                        $positionIds = null; //公司id集合
                        foreach ($position as $key => $value) {
                            $positionIds .= $value['id'] . ',';
                        }
                        if (!empty($positionIds))
                            $positionIds = rtrim($positionIds, ','); //剔除最后一个，逗号

                        //获取下属部门 人员信息
                        $testDo->where = "career in($positionIds)";
                        $api = new UserServiceClient(null);
                        \ApiClient::build($api);
                        $rs = $api->userList($testDo);
                        $UserList = $rs->data;
                        if (isset($UserList)) {
                            foreach ($UserList as $kk => $uVal) {
                                $userIds .= ($kk == 0 ? ',' : '') . $uVal['userid'] . ',';
                            }
                            if (!empty($userIds))
                                $userIds = rtrim($userIds, ','); //剔除最后一个，逗号
                        } else {
                            $userIds = null;
                        }
                    }
                } else {
                    $userIds = null;
                }

                $userIds = explode(',', $userIds); //转换数组
                $userIds = array_unique($userIds); //去重
                $userIds = implode(',', $userIds); //去重

                break;
            // 属于公司级别
            case 1 :
                //**根据公司id查询 部门级别
                $department = Db::name('department')->where('status = 1 AND isdelete = 0 AND company_id = (' . $id . ')')->field('id,name')->select();
                if (isset($department)) {
                    $departmentIds = null; //公司id集合
                    foreach ($department as $key => $value) {
                        $departmentIds .= $value['id'] . ',';
                    }
                    if (!empty($departmentIds))
                        $departmentIds = rtrim($departmentIds, ','); //剔除最后一个，逗号
    
                    //获取下属部门 人员信息
                    $testDo->where = "department in($departmentIds)";
                    $api = new UserServiceClient(null);
                    \ApiClient::build($api);
                    $rs = $api->userList($testDo);
                    $UserList = $rs->data;
                    if (isset($UserList)) {

                        foreach ($UserList as $kk => $uVal) {
                            $userIds .= $uVal['userid'] . ',';
                        }
                        if (!empty($userIds))
                            $userIds = rtrim($userIds, ','); //剔除最后一个，逗号
                    } else {
                        $userIds = null;
                    }
                    //**根据部门id查询 职务级别
                    $position = Db::name('admin_position')->where('p_status = 1 AND isdelete = 0 AND department_id in (' . $departmentIds . ')')->field('id,name')->select();
                    if (isset($position)) {
                        $positionIds = null; //公司id集合
                        foreach ($position as $key => $value) {
                            $positionIds .= $value['id'] . ',';
                        }
                        if (!empty($positionIds))
                            $positionIds = rtrim($positionIds, ','); //剔除最后一个，逗号
       
                        //获取下属部门 人员信息
                        $testDo->where = "career in($positionIds)";
                        $api = new UserServiceClient(null);
                        \ApiClient::build($api);
                        $rs = $api->userList($testDo);
                        $UserList = $rs->data;
                        if (isset($UserList)) {
                            foreach ($UserList as $kk => $uVal) {
                                $userIds .= ($kk == 0 ? ',' : '') . $uVal['userid'] . ',';
                            }
                            if (!empty($userIds))
                                $userIds = rtrim($userIds, ','); //剔除最后一个，逗号
                        } else {
                            $userIds = null;
                        }
                    }
                } else {
                    $userIds = null;
                }
                $userIds = explode(',', $userIds); //转换数组
                $userIds = array_unique($userIds); //去重
                $userIds = implode(',', $userIds); //去重
                break;
            // 属于部门级别
            case 2 :
                //**根据部门id查询 职务级别
                $position = Db::name('admin_position')->where('p_status = 1 AND isdelete = 0 AND department_id = (' . $id . ')')->field('id,name')->select();
                if (isset($position)) {
                    $positionIds = null; //公司id集合
                    foreach ($position as $key => $value) {
                        $positionIds .= $value['id'] . ',';
                    }
                    if (!empty($positionIds))
                        $positionIds = rtrim($positionIds, ','); //剔除最后一个，逗号

                    //获取下属部门 人员信息
                    $testDo->where = "career in($positionIds)";
                    $api = new UserServiceClient(null);
                    \ApiClient::build($api);
                    $rs = $api->userList($testDo);
                    $UserList = $rs->data;
                    if (isset($UserList)) {
                        foreach ($UserList as $kk => $uVal) {
                            $userIds .= $uVal['userid'] . ',';
                        }
                        if (!empty($userIds))
                            $userIds = rtrim($userIds, ','); //剔除最后一个，逗号
                    } else {
                        $userIds = null;
                    }
                } else {
                    $userIds = null;
                }
                $userIds = explode(',', $userIds); //转换数组
                $userIds = array_unique($userIds); //去重
                $userIds = implode(',', $userIds); //去重
                break;
            // 属于职务级别
            case 3 :

                break;
            // 属于
            case -1 :

                break;
            /*             * **打个补丁 预防id不等于2**** */
            default:
            /*             * **打个补丁 end**** */
        }
        return $userIds;
    }

    /**
     * 根据用户ids集合获取 用户参加的正式考试
     * @param $ids
     * @param string $condition
     * @return mixed
     */
    public function getExamInfoByUserids($ids, $condition = 1,$order = null,$page=0)
    {	
		$pages = $page*10;
        $where = empty($condition) ? 'ep_type =2' : "ep_type =2 and {$condition}";
        $order = empty($order) ?['b.modified'=>'desc'] : $order;
        $where .= $ids && !empty($ids) ? " AND a.identity_id in({$ids})" : " AND ep_userid in('0')";
        $ExamInfo = Db::name('exams_papers')
                        ->alias('a')
                        ->join("papers_info b", "a.ep_infoId = b.id", 'left')
                        ->join("user_company c", "a.identity_id = c.id", 'left')
                        ->join("user d", "d.userid = c.userid", 'left')
                        ->field('b.modified,b.name,b.modified,b.scorelist,a.basicid,a.ispass,a.identity_id,c.scores,a.ep_paper_name,d.realname,b.starttime,d.photo')
                        ->where($where)
                        ->order($order)->limit($pages.',10')->select();
        return $ExamInfo;
    }

    /**
     * 根据条件判断 当前用户是否为公司管理者
     */
    public function getIsIntendantByArg($userid, $companyid)
    {
        $arr = Db::name('company')->where('status=1 and intendant=' . $userid . ' and id=' . $companyid)->find();
        return $arr;
    }

    /**
     * 根据公司Id获取下属信息
     */
    public function getSubordinateInfoBycompanyid($companyid)
    {
        $user = Db::name('user')
            ->alias('a')
            ->where('a.status = 1 AND a.isdelete = 0 AND b.company_id in (' . $companyid . ')')
            ->field('b.id identity_id,a.userid,a.username,a.realname,a.scores,a.userid')
            ->join('user_company b','a.userid=b.userid')
            ->select();
        return $user;
    }

    /**
     * 根据公司Id获取下属信息
     */
    public function getGdlUserIdByUsername($Username)
    {
        $user = Db::table('lanhui.gdl_member')->where(['username' => $Username])->field('userid')->find();
        return $user;
    }

    public function getUserIdByUsername($Username)
    {
        $user = Db::name('user')->where(['username' => $Username])->field('userid')->find();
        return $user;
    }
    
    public function getUserInfoByIdcard($idcard)
    {
        $user = Db::name('user')->where(['idcard' => $idcard])->field('userid,username,idcard')->find();
        return $user;
    }

    //获取注册时间列表
    public function getUserRegTimeList()
    {
        $child_plaform = getChildAdminRegByPlaformId($this->plaform);
        $user = $this->where(['isdelete' => 0, 'admin_reg'=>['in',$child_plaform], 'status' => 1])->field('userregtime')->group('userregtime')->order('userregtime', 'asc')->select();
        return $user;
    }

	 //通过用户名模糊查询用户id
    public function getUserRegID($username,$field='*')
    {
        $user = $this->where(['a.isdelete' => 0,  'a.status' => 1,'a.realname'=>['like','%'.trim($username).'%']])->alias('a')->join("user_company b", "a.userid = b.userid", 'right')->field($field)->select();
        return $user;
    }


        //留底照片审核状态修改
    public function updateVerifyPhoto($data,$userid,$status=0){
        if (empty($data)){
            $arr = $this->where("userid", $userid)->update(['vface'=>$status]);
        }else{
            $arr = $this->where("userid", $userid)->update(['photo_collect'=>$data,'vface'=>$status]);
        }
        return $arr;
    }

    //获取单条照片审核
    public function getVerifyPhotoById($userid){
        $arr = $this->where(['userid'=>$userid])->field('userid,photo_collect,vface')->find();
        return $arr;
    }



}
